/********************************************************/
/*	Author:		gong_libin			*/
/*	Date:		2017_11_01			*/
/*	File:		CmConfig.cpp			*/
/********************************************************/

#include "CmConfig.h"

CCmConfig::CCmConfig()
{
	m_ppCTrans = NULL;
	memset(&m_stKafka, '\0', sizeof(CMKAFKA_S));
	memset(&m_stGlobal, '\0', sizeof(CMGLOBAL_S));
	m_CRedis.CmSetInit(CM_NUM_RDS, sizeof(CMSTR_C**));
}

CCmConfig::~CCmConfig()
{
	this->CmConfigSetDestroy();
	m_CRedis.CmSetDestroy();
	m_CTrans.CmMapClear();
	m_ppCTrans = NULL;
}

int CCmConfig::CmConfigLoad(char* pszFile)
{
	int iReturn = 0;

	if (CM_SUCCESS == CmConfOpen(pszFile)) {
		iReturn = CmConfigGlobal() | CmConfigKafka() | CmConfigRedis() | CmConfigCTrans();
		CmConfClose();
	}
	else {
		iReturn = CM_FAILURE;
	}

	return iReturn;
}

void CCmConfig::CmConfigPrint()
{
	CM_PRINT("global.did = %s\n", m_stGlobal.m_szDid);
	CM_PRINT("global.port = %s\n", m_stGlobal.m_szPort);
	CM_PRINT("global.timeout = %s\n", m_stGlobal.m_szTmOut);
	CM_PRINT("global.logger = %s\n", m_stGlobal.m_szLogger);

	CM_PRINT("kafka.topic = %s\n", m_stKafka.m_szTopic);
	CM_PRINT("kafka.broker = %s\n", m_stKafka.m_szBroke);

	for (ULONG ulIdx = 0; ulIdx < m_CRedis.CmSetGetCount(); ulIdx ++) {
		CM_PRINT("[%03ld]: %s\n", ulIdx + 1, (*(CMSTR_C**)m_CRedis.CmSetIndexGet(ulIdx))->c_str());
	}

	m_CTrans.CmMapDisplay();

	return;
}

int CCmConfig::CmConfigGlobal()
{
	char szBuf[CM_BUFFER] = {'\0'};

	CM_CFG_VALUES(CM_CFG_GLOBAL, CM_CFG_DID, m_stGlobal.m_szDid, CM_VAL_STR);
	CM_CFG_VALUES(CM_CFG_GLOBAL, CM_CFG_PORT, m_stGlobal.m_szPort, CM_VAL_STR);
	CM_CFG_VALUES(CM_CFG_GLOBAL, CM_CFG_TMOUT, m_stGlobal.m_szTmOut, CM_VAL_STR);
	CM_CFG_VALUES(CM_CFG_GLOBAL, CM_CFG_LOGGER, m_stGlobal.m_szLogger, CM_VAL_STR);

	return CM_SUCCESS;
}

int CCmConfig::CmConfigKafka()
{
	char szBuf[CM_BUFFER] = {'\0'};

	CM_CFG_VALUES(CM_CFG_KAFKA, CM_CFG_TOPIC, m_stKafka.m_szTopic, CM_VAL_STR);
	CM_CFG_VALUES(CM_CFG_KAFKA, CM_CFG_BROKER, m_stKafka.m_szBroke, CM_VAL_STR);

	return CM_SUCCESS;
}

int CCmConfig::CmConfigRedis()
{
	char szBuf[CM_BUFFER] = {'\0'};
	char *pszKey = NULL, *pszVal = NULL;

	CM_CFG_KVHEAD(CM_CFG_REDIS, pszKey, pszVal) {
		CMSTR_C* pCAddr = new CMSTR_C(pszVal);
		m_CRedis.CmSetIndexPut(m_CRedis.CmSetGetCount(), &pCAddr);
	} CM_CFG_KVTAIL();

	return CM_SUCCESS;
}

int CCmConfig::CmConfigCTrans()
{
	char szBuf[CM_BUFFER] = {'\0'};
	char *pszKey = NULL, *pszVal = NULL;

	CM_CFG_KVHEAD(CM_CFG_TRANS, pszKey, pszVal) {
		CMSTR_C CKey(pszKey);
		CMSTR_C CVal(pszVal);
		m_CTrans.CmMapInsert(CKey, CVal);
	} CM_CFG_KVTAIL();

	return CM_SUCCESS;
}

void CCmConfig::CmConfigSetDestroy()
{
	for (ULONG ulIdx = 0; ulIdx < m_CRedis.CmSetGetCount(); ulIdx ++) {
		delete *(CMSTR_C**)m_CRedis.CmSetIndexGet(ulIdx);
	}

	return;
}
